package xyz.zhzby.cyzx.ucenter.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import xyz.zhzby.cyzx.servicebase.exception.BusinessException;

/**
 * @author zby
 * @date 2021/12/19
 */
@Component
@ApiModel(description = "短信相关封装")
public class SmsUtils implements InitializingBean {

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    @Value("${aliyun.sms.signName}")
    private String signName;

    private static String ACCESS_KEY_ID;

    private static String ACCESS_KEY_SECRET;

    private static String TEMPLATE_CODE;

    private static String SIGN_NAME;

    @ApiModelProperty("不要动，默认使用官方的")
    private static final String REGION_ID = "cn-hangzhou";

    @ApiModelProperty("产品名称:云通信短信API产品,开发者无需替换")
    private static final String PRODUCT = "Dysmsapi";

    @ApiModelProperty("产品域名,开发者无需替换")
    private static final String DOMAIN = "dysmsapi.aliyuncs.com";

    @Override
    public void afterPropertiesSet() throws Exception {
        ACCESS_KEY_ID = accessKeyId;
        ACCESS_KEY_SECRET = accessKeySecret;
        TEMPLATE_CODE = templateCode;
        SIGN_NAME = signName;
    }

    @ApiOperation("封装短信验证码发送，目前只有验证码所以这样写，后期有复杂短信可再改")
    public static void sendVerificationCode(String phone, String code) throws ClientException {

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(SIGN_NAME);
        request.setTemplateCode(TEMPLATE_CODE);
        String templateParam = "{\"code\":\"" + code + "\"}";
        request.setTemplateParam(templateParam);

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        DefaultProfile.addEndpoint(REGION_ID, PRODUCT, DOMAIN);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        request.setOutId("yourOutId");

        acsClient.getAcsResponse(request);
    }

}
